﻿// Copyright 2006 - Ricardo Stuven (rstuven@gmail.com)
//
// This file is part of MsSqlSpatial.
// MsSqlSpatial is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// MsSqlSpatial is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public License
// along with MsSqlSpatial; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 

using System.Data.SqlTypes;
using GeoAPI.Geometries;
using GisSharpBlog.NetTopologySuite.LinearReferencing;
using Microsoft.SqlServer.Server;
using MsSqlSpatial;

public partial class UserDefinedFunctions
{
    /// <summary>
    /// PostGIS docs:
    /// 
    /// line_locate_point(LineString, Point)
    /// 
    /// Returns a float between 0 and 1 representing the location of the closest point
    /// on LineString to the given Point, as a fraction of total 2d line length. 
    /// 
    /// You can use the returned location to extract a Point (line_interpolate_point) or a substring (line_substring). 
    /// 
    /// </summary>
    /// <param name="ewkb"></param>
    /// <returns></returns>
    [SqlFunction(IsDeterministic = true)]
    public static SqlDouble LineLocatePoint(SqlBytes ewkbLinestring, SqlBytes ewkbPoint)
    {
        IGeometry pairLinestring = ConvertGeometry.ToGeometry(ewkbLinestring);
        if (pairLinestring is ILineString)
        {
            var pairPoint = ConvertGeometry.ToGeometry(ewkbPoint) as IPoint;
            if (pairPoint != null)
            {
                var indexedLine = new LengthIndexedLine(pairLinestring);
                double index = indexedLine.Project(pairPoint.Coordinate);
                return new SqlDouble(index/pairLinestring.Length);
            }
        }
        return SqlDouble.Null;
    }
} ;